package com.wewoo.log4e.starter.mongodb.spring.boot.autoconfigure;

import com.mongodb.ConnectionString;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.wewoo.log4e.core.util.ReadLogUtil;
import com.wewoo.log4e.starter.mongodb.action.ReadLogMongoDBUtil;
import com.wewoo.log4e.starter.mongodb.executor.MongodbExecutor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName DataSourceLogConfiguration
 * @Description TODO
 * @Author tangjin
 * @Date 16:57 2022/2/14
 **/
@Configuration
@EnableConfigurationProperties(Log4eMongoDBProperties.class)
@ConditionalOnMissingBean(MongoDatabaseFactory.class)
public class MongoDBLogAutoConfiguration {

    @Bean(name = "mongoDbFactory")
    public MongoDatabaseFactory mongoDbFactory(Log4eMongoDBProperties properties) {
        StringBuilder stringBuilder=new StringBuilder("mongodb://#:%@");
        for (String address : properties.getAddress()) {
            stringBuilder.append(address);
        }
        stringBuilder.append("/").append(properties.getDatabase());
        String uri=stringBuilder.toString().replace("#",properties.getUsername()).replace("%",properties.getPassword());
        ConnectionString connectionString=new ConnectionString(uri);
        MongoClient mongoClient = MongoClients.create(connectionString);
        return new SimpleMongoClientDatabaseFactory(mongoClient, properties.getDatabase());
    }



    @Bean
    public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDatabaseFactory){
        return new MongoTemplate(mongoDatabaseFactory);
    }

    @Bean
    @Order(200)
    @ConditionalOnMissingBean
    public MongodbExecutor mongoDataSourceExecutor(MongoTemplate mongoTemplate) {
        return new MongodbExecutor(mongoTemplate);
    }

    @Bean
    public ReadLogMongoDBUtil readLogMongoDBUtil(MongoTemplate mongoTemplate){
        return ReadLogMongoDBUtil.builder().mongoTemplate(mongoTemplate).build();
    }
}
